package com.hex.ds.hdrs.agent.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.hex.bigdata.hbda.base.Page;
import com.hex.bigdata.hbda.utils.FileUtil;
import com.hex.ds.hdrs.agent.converter.IAgentToBizAgentConverter;
import com.hex.ds.hdrs.agent.dao.AgentConfDao;
import com.hex.ds.hdrs.agent.dto.AgentSessionResponseDto;
import com.hex.ds.hdrs.agent.po.AgentConf;
import com.hex.ds.hdrs.agent.vo.*;
import com.hex.ds.hdrs.app.dto.AppAdminRelationDto;
import com.hex.ds.hdrs.app.po.AppAdminRelationPo;
import com.hex.ds.hdrs.app.po.AppAgentRelationPo;
import com.hex.ds.hdrs.app.service.IAppAdminRelationService;
import com.hex.ds.hdrs.app.service.IAppAgentRelationService;
import com.hex.ds.hdrs.app.vo.AppAgentVo;
import com.hex.ds.hdrs.center.service.CenterManager;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.constant.ErrorCode;
import com.hex.ds.hdrs.common.exception.BizException;
import com.hex.ds.hdrs.common.helper.RamHelper;
import com.hex.ds.hdrs.common.utils.BaseUtil;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.common.utils.HttpUtils;
import com.hex.ds.hdrs.common.utils.MapUtil;
import com.hex.ds.hdrs.log.po.LogReq;
import com.hex.ds.hdrs.period.task.po.PeriodTask;
import com.hex.ds.ra.common.base.BaseRespInfo;
import com.hex.ds.ra.model.AgentInfModel;
import com.hex.ds.ra.model.BizAgentModel;
import com.hex.ds.ra.model.dto.AgentInfDto;
import com.hex.ds.ra.service.AgentInfService;
import com.hex.ds.ra.service.BizAgentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package: com.hex.ds.hdrs.agent.service
 * @ClassName AgentConfService
 * @Description: 节点定义表 服务实现类
 * @Author: jd.chen
 * @Date 2021/6/24 16:19
 * @Version v1.0
 **/
@Slf4j
@Service
public class AgentConfService {

    @Autowired
    private AgentManager agentManager;

    @Autowired
    private AgentConfDao agentConfDao;

    @Autowired
    private CenterManager centerManager;

    @Autowired
    private IAppAdminRelationService appAdminRelationService;

    @Autowired
    private IAppAgentRelationService appAgentRelationService;

    @Autowired
    private BizAgentService bizAgentService;

    @Autowired
    private AgentInfService agentInfService;

    @Autowired
    private IAgentToBizAgentConverter iAgentToBizAgentConverter;

    public List<AgentConf> qryAgentConfByAppCode(String appCode) {
        log.info("查询app Code 【AgentConfService.qryAgentConfByAppCode】开始=========》");
        Map map = new HashMap(16);
        map.put("appCode", appCode);
        return agentConfDao.qryAgentConfList(map);
    }

    public List<AgentConf> qryAgentConfByAppCodes(List<String> appCodeList) {
        appCodeList = appCodeList.stream().distinct().collect(Collectors.toList());
        Map map = new HashMap(16);
        map.put("appCodeList", appCodeList);
        return agentConfDao.qryAgentList(map);
    }

    public AgentConf qryAgentConfByAgentCode(String agentCode) {
        Map map = new HashMap(16);
        map.put("agentCode", agentCode);
        log.info("查询agent Code【AgentConfService.qryAgentConfByAgentCode】开始=========》");
        return agentConfDao.qryAgentConf(map);
    }

    public AgentConf qryAgentConfByIp(String ip) {
        Map map = new HashMap(16);
        map.put("agentIp", ip);
        log.info("查询agent_ip【AgentConfService.qryAgentConfByAgentCode】开始=========》");
        return agentConfDao.qryAgentConf(map);
    }

    public List<AgentConf> qryAgentConfList() {
        log.info("查询agent confList 【AgentConfService.qryAgentConfList】开始=========》");
        return agentConfDao.qryAgentList();
    }

    public List<AgentConf> qryAgentConfList(Map map) {
        log.info("查询agentConfList 【AgentConfService.qryAgentConfList】开始=========》");
        return agentConfDao.qryAgentList(map);
    }

    public List<AgentConf> selectAll(AgentConf agentConf, Page page) {
        log.info("进入了AgentConfService类中的selectAll方法");
        Map map = MapUtil.convertObjToMap(agentConf);
        return this.agentConfDao.qryAgentPage(map, page);
    }


    /**
     * @Method: add
     * @Param: [agentConf, maxAgentNum]
     * @Return: void
     * @Description： 新增节点
     * @Author： jd.chen
     * @Date： 2021/6/24 16:11
     * @Version： V1.0
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void add(AgentConf agentConf) {
        log.info("进入了AgentConfService类中的add方法");

        int maxConcurrentNum = centerManager.getMaxConcurrentNum();
        int maxAgentNum = centerManager.getMaxAgentNum();

        maxConcurrentNum -= agentConf.getConcurrentNum();
        this.checkLisenceForAddAgent(maxAgentNum, maxConcurrentNum);

        this.initAgentConf(agentConf);
        this.agentConfDao.add(agentConf);
    }

    /**
     * @Method: checkLisenceForAddAgent
     * @Param: [maxAgentNum, maxConcurrentNum]
     * @Return: void
     * @Description： 新增agent，校验lisence
     * @Author： jd.chen
     * @Date： 2021/6/24 16:41
     * @Version： V1.0
     */
    public void checkLisenceForAddAgent(int maxAgentNum, int maxConcurrentNum) {
        // 校验节点配置数是否超过限制
        int agentNum = this.qryAgentCount();
        if (agentNum >= maxAgentNum) {
            log.error("节点配置数超过限制数，不允许添加！");
            throw new BizException(ErrorCode.ERROR_840002);
        }

        // 校验并发数是否超过限制
        int concurrentNum = this.agentConfDao.qryConcurrentNum();
        if (concurrentNum >= maxConcurrentNum) {
            log.error("节点总并发数超过限制数，不允许添加！");
            throw new BizException(ErrorCode.ERROR_840004);
        }
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteByIds(List<String> ids) {
        log.info("进入了AgentConfService类中的deleteByIds方法");
        if (CollectionUtil.isEmpty(ids)) {
            throw new BizException(ErrorCode.ERROR_910001);
        }
        if (!CollectionUtil.isEmpty(ids)) {
            for (String id : ids) {
                Map map = new HashMap(16);
                map.put("pkId", id);
                AgentConf agentConf = this.agentConfDao.qryAgentConf(map);
                List<AppAgentRelationPo> appAgentRelationPos = this.appAgentRelationService.queryListByAgentCode(agentConf.getAgentCode());
                if (!CollectionUtil.isEmpty(appAgentRelationPos)) {
                    throw new BizException("910001", "节点【" + agentConf.getAgentName() + "】在关联表中存在，无法删除");
                } else {
                    this.agentConfDao.deleteById(id);
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void update(AgentConf agentConf) {
        log.info("进入了AgentConfService类中的update方法");
        agentConf.setUpTs(HdrsDateUtil.getCurTs());
        Map<String, String> map = MapUtil.convertObjToMap(agentConf);
        this.agentConfDao.update(map);

        //更新agentSession
        AgentSession session = agentManager.getSession(agentConf.getAgentCode());
        if (session != null) {
            session.setAgentConf(agentConf);
        }
    }

    /**
     * 更新节点状态信息
     *
     * @param agentConf
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateAgentStatus(AgentConf agentConf) {
        log.debug("进入了AgentConfService类中的updateAgentStatus方法");
        Map map = new HashMap(16);
        map.put("agentStatus", agentConf.getAgentStatus());
        map.put("agentCode", agentConf.getAgentCode());
        map.put("pkId", agentConf.getPkId());
        int a = this.agentConfDao.update(map);
        if (a > 0) {
            agentManager.updateAgentStatus(agentConf);
        }
    }

    /**
     * 更新节点最后接受时间信息
     *
     * @param map
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public String updateAgentLstTime(Map map) {
        log.debug("进入了AgentConfService类中的updateAgentStatus方法");
        int a = this.agentConfDao.updateAgentLstTime(map);
        if (a > 0) {
            return "success";
        }
        return "error";
    }

    /**
     * 更新节点状态信息
     *
     * @param map
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateAgentStatus(Map map) {
        this.agentConfDao.updateAgentStatus(map);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateAgentStatus(String agentCode, String agentStatus){
        Map map = new HashMap();
        map.put("agentCode", agentCode);
        map.put("agentStatus", agentStatus);
        this.agentConfDao.updateAgentByCode(map);
    }

    public void updateAgentVersion(String agentCode, String serverVer){
        Map map = new HashMap();
        map.put("agentCode", agentCode);
        map.put("serverVer", serverVer);
        this.agentConfDao.updateAgentByCode(map);
    }

    public Boolean checkRepeatCode(String agentCode) {
        log.info("进入了【AgentConfService类中的updateAgentStatus方法】参数agentCode: {}", agentCode);
        return this.agentConfDao.checkRepeatCode(agentCode) > 0;
    }

    public AgentInfoEchars chartData(Integer time, String type) {
        AgentInfoEchars infoEchars = new AgentInfoEchars();
        List<String> day = new ArrayList<>();
        for (int i = 1; i <= time; i++) {
            day.add(String.valueOf(i) + type);
        }
        // 设置时间
        infoEchars.setDayArray(day.toArray(new String[day.size()]));
        // 根据时间查询Agent的资源信息
        return infoEchars;
    }

    /**
     * 查询节点编码集合
     *
     * @return
     */
    public List<String> selectCodes() {
        return this.agentConfDao.selectCodes();
    }

    public List<AppAgentRelationPo> qryNodeInfo(String appCode) {
        log.debug("进入了AgentConfService中的qryNodeCode方法");
        Map<String, Object> map = new HashMap<>(16);
        map.put("agentStatus", "1");
        List<AgentConf> list = this.agentConfDao.qryAgentList(map);
        List<AppAgentRelationPo> appAgentRelationPos = appAgentRelationService.queryListByAppCode(appCode);
        return this.getAgentConfList(list, appAgentRelationPos, appCode);
    }

    /**
     * 计算每个节点剩余资源数和并发数
     *
     * @param list
     * @param appAgentRelationPos
     * @param appCode
     * @return
     */
    private List getAgentConfList(List<AgentConf> list, List<AppAgentRelationPo> appAgentRelationPos, String appCode) {
        List agentConfList = new ArrayList<>();
        for (AgentConf agentConf : list) {
            Map map = new HashMap(16);
            map.put("label", agentConf.getAgentName());
            map.put("value", agentConf.getAgentCode());
            // map.put("maxResNum",agentConf.getResNum());
            // map.put("maxConNum",agentConf.getConcurrentNum());
            map.put("disabled", false);
            for (AppAgentRelationPo agentRelation : appAgentRelationPos) {
                // if (!agentRelation.getAppCode().equals(appCode) &&
                // agentConf.getAgentCode().equals(agentRelation.getAgentCode()))
                // {
                // Integer maxResNum = (Integer) map.get("maxResNum");
                // Integer maxConNum = (Integer) map.get("maxConNum");
                // map.put("maxResNum",maxResNum - maxResNum *
                // agentRelation.getAgentWeight() / 100);
                // map.put("maxConNum",maxConNum - maxConNum *
                // agentRelation.getAgentWeight() / 100);
                // }
                if (agentRelation.getAppCode().equals(appCode)
                        && agentConf.getAgentCode().equals(agentRelation.getAgentCode())) {
                    map.put("disabled", true);
                }
            }
            agentConfList.add(map);
        }
        return agentConfList;
    }

    /**
     * 获取某个用户所属节点列表
     *
     * @return
     */
    public List<AppAgentVo> findNodeByUser(String username) {
        log.info("进入了【AgentConfService类中的findNodeByUser方法】参数：{}", username);
        return this.agentConfDao.qryNodeByUser(username);
    }

    /**
     * 获取某个用户所属节点AgentCode列表
     *
     * @param username
     * @return
     */
    public List<String> findAgentCodeByUser(String username) {
        log.info("进入了【AgentConfService类中的findAgentCodeByUser方法】参数：{}", username);
        return this.agentConfDao.qryAgentCodeByUser(username);
    }

    /**
     * 查询某应用管理员是否拥有在该节点下所有app的权限
     *
     * @param agentCode
     * @return
     */
    public String qryHaveApp(String agentCode) {
        // 当前用户
        String userName = BaseUtil.getUserId();
        // 返回没有权限的appCode
        List<String> res = new ArrayList<String>();
        // 根据节点编码查询所有appCode
        List<AppAgentRelationPo> nodeInfoByAgentCodes = appAgentRelationService.queryListByAgentCode(agentCode);
        for (AppAgentRelationPo appAgentRelationPo : nodeInfoByAgentCodes) {
            // 判断是否拥有此app权限
            boolean appFlag = false;
            AppAdminRelationDto appAdminRelationDto = new AppAdminRelationDto().setAppCode(appAgentRelationPo.getAppCode());
            List<AppAdminRelationPo> userListByAppCode = appAdminRelationService.queryList(appAdminRelationDto);
            for (AppAdminRelationPo appAdminRelationPo : userListByAppCode) {
                if (userName.equals(appAdminRelationPo.getAdminUserName())) {
                    appFlag = true;
                    break;
                }
            }
            if (!appFlag) {
                // 没有此app的权限
                if (!res.contains(appAgentRelationPo.getAppCode())) {
                    res.add(appAgentRelationPo.getAppCode());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(res)) {
            return "false";
        } else {
            return "true";
        }
    }

    /**
     * 根据某节点获取服务器密码
     *
     * @param agentCode
     * @return
     */
    public String qryPwdByCode(String agentCode) {
        AgentConf agentConf = new AgentConf();
        agentConf.setAgentCode(agentCode);
        Map map = MapUtil.convertObjToMap(agentConf);
        AgentConf qryAgentConf = agentConfDao.qryAgentConf(map);
        return qryAgentConf.getServerPwd();
    }

    /**
     * 检查重复名称
     *
     * @param agentName
     * @return
     */
    public Boolean checkAgentName(String agentName) {
        log.info("进入了【AgentConfService类中的checkAgentName方法】参数：{}", agentName);
        return this.agentConfDao.checkAgentName(agentName) > 0;
    }

    /**
     * 检查重复名称
     *
     * @param agentIp
     * @return
     */
    public Boolean checkAgentIP(String agentIp) {
        log.info("进入了【AgentConfService类中的checkAgentIP方法】参数：{}", agentIp);
        return this.agentConfDao.checkAgentIP(agentIp) > 0;
    }

    /**
     * 查询agent数量
     *
     * @return
     */
    public Integer qryAgentCount() {
        return this.agentConfDao.qryAgentCount();
    }

    /**
     * @Method: selectPageBySessionList
     * @Param: [agentCode, page]
     * @Return: java.util.List<com.hex.ds.hdrs.period.task.po.PeriodTask>
     * @Description： 根据AgentCode获取session中的task信息
     * @Author： jd.chen
     * @Date： 2021/7/4 10:55
     * @Version： V1.0
     */
    public List<PeriodTask> selectPageBySessionList(String agentCode, Page page) {
        AgentSession agentSession = agentManager.getAgentSession(agentCode);
        List<PeriodTask> resultList = agentSession.getPeriodRunningList();

        if (CollectionUtils.isEmpty(resultList)) {
            return resultList;
        }
        Integer startIndex = page.getPageIndex() * page.getPageSize();
        Integer endIndex = (page.getPageIndex() + 1) * page.getPageSize();
        if (startIndex == resultList.size()) {
            startIndex = (page.getPageIndex() - 1) * page.getPageSize();
            page.setPageIndex(page.getPageIndex() - 1);
        } else if (startIndex > resultList.size()) {
            Integer pageIndex = resultList.size() / page.getPageSize();
            startIndex = pageIndex * page.getPageSize();
            page.setPageIndex(pageIndex);
        }
        endIndex = (endIndex < resultList.size()) ? endIndex : resultList.size();
        return resultList.subList(startIndex, endIndex);
    }

    /**
     * 下载节点日志
     *
     * @param response
     * @param request
     * @param agentConf
     */
    public void downloadAgentLog(HttpServletResponse response, HttpServletRequest request, AgentConf agentConf) {
        Map<String, Object> map = new HashMap<>(16);
        //日志文件压缩后的文件名称
        map.put("fileName", agentConf.getAgentCode() + ".zip");
        //下载到中心的文件名称
        String localPath = "/downLoadAgentLog/";
        File f = new File(localPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        String filePath = localPath + agentConf.getAgentCode() + ".zip";
        HttpUtils.httpDownFile("http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/downAgentLog", map, "utf-8", filePath);
        File file = new File(filePath);
        if (file.exists()) {
            //文件下载后删除
            FileUtil.downloadFile(request, response, file, true);
        }
    }

    /**
     * @Method: qryCatalogue <br>
     * @Param: [agentConf] <br>
     * @Return: java.util.List<com.hex.ds.hdrs.agent.model.vo.Catalogue> <br>
     * @Description：查看日志目录<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/11 15:15 <br>
     * @Version： V1.0<br>
     */
    public List<Catalogue> qryCatalogue(AgentConf agentConf) {
        String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/qryCatalogue";
        String back = HttpUtils.httpJsonGet(url, null);
        ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
        List<Catalogue> catalogues = (List<Catalogue>) rsp.getRsd();
        return catalogues;
    }

    /**
     * @Method: previewLog <br>
     * @Param: [agentConf] <br>
     * @Return: java.lang.String <br>
     * @Description：日志在线预览<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/16 10:29 <br>
     * @Version： V1.0<br>
     */
    public String previewLog(AgentConf agentConf) {
        String res = "";
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/previewLog";
            LogReq logReq = new LogReq();
            logReq.setLogPath(agentConf.getLogPath());
            logReq.setLogType(agentConf.getLogType());
            String back = HttpUtils.httpJsonPost(url, logReq);
            ResponseInf rsp = JSONArray.parseObject(back, ResponseInf.class);
            res = (String) rsp.getRsd();
        } catch (Exception e) {
            log.error("日志在线预览失败，原因:{}", e.getMessage(), e);
        }
        return res;
    }

    /**
     * @Method: checkConnect
     * @Param: [agentConf]
     * @Return: java.lang.String
     * @Description： 检查节点连接状态
     * @Author： jd.chen
     * @Date： 2021/7/4 10:50
     * @Version： V1.0
     */
    public String checkConnect(AgentConf agentConf) {
        if (this.agentManager.testLink(agentConf)) {
            return "SUCCESS";
        } else {
            return "ERROR";
        }
    }

    /**
     * 通过当前应用查找节点信息
     *
     * @param
     * @return
     */
    public List<AppAgentVo> findNodeByCurrentApp(String appCode) {
        log.info("进入了【AgentConfService类中的findNodeByCurrentApp方法】");
        List<AppAgentVo> list = agentConfDao.qryNodeByCurrentApp(appCode);
        for (AppAgentVo appAgentVo : list) {
            RamHelper.getAgentUsageRate(appAgentVo);
        }
        return list;
    }

    /**
     * 获取当前用户所属节点列表
     *
     * @return
     */
    public List<AppAgentVo> findNodeByCurrentUser() {
        log.info("进入了【AgentConfService类中的findNodeByCurrentUser方法】");
        String username = BaseUtil.getUserId();
        List<AppAgentVo> list = this.findNodeByUser(username);
        if (CollectionUtils.isNotEmpty(list)) {
            for (AppAgentVo appAgentVo : list) {
                RamHelper.getAgentUsageRate(appAgentVo);
            }
        }
        return list;
    }

    /**
     * 查询内存有效节点
     *
     * @param agentSession
     * @param page
     * @return
     */
    public List<AgentSessionVO> qryAgentSession(AgentSessionVO agentSession, Page page) {
        List<AgentSessionVO> agentSessionVOList = new ArrayList<AgentSessionVO>();
        List<AgentSession> agentSessionList = agentManager.getAgentSessionList();
        List<AgentSession> agentSessionListShow = new ArrayList<AgentSession>();
        // 条件过滤
        if (StringUtils.isNotBlank(agentSession.getAgentCode())) {
            for (AgentSession agentSession2 : agentSessionList) {
                if (agentSession2.getAgentCode().equals(agentSession.getAgentCode())) {
                    agentSessionListShow.add(agentSession2);
                }
            }
        } else {
            agentSessionListShow = agentSessionList;
        }
        for (AgentSession agentSession2 : agentSessionListShow) {
            AgentSessionVO agentSessionVO = new AgentSessionVO();
            agentSessionVO.setAgentCode(agentSession2.getAgentCode());
            agentSessionVO.setLstHeartBeatTs(String.valueOf(agentSession2.getLstHeartBeatTs()));
            agentSessionVO.setRegisterTs(agentSession2.getRegisterTs());
            agentSessionVO.setStatus(agentSession2.getStatus());
            agentSessionVOList.add(agentSessionVO);
        }
        // 结果分页
        return RamHelper.formatAgentListPage(agentSessionVOList, page);
    }

    /**
     * 查询内存无效节点
     *
     * @param agentSession
     * @param page
     * @return
     */
    public List<AgentSessionVO> qryNotValidAgentSession(AgentSessionVO agentSession, Page page) {
        List<AgentSessionVO> agentSessionVOList = new ArrayList<AgentSessionVO>();
        List<AgentSession> agentSessionList = agentManager.getNotValidAgentSessionList();
        List<AgentSession> agentSessionListShow = new ArrayList<AgentSession>();

        // 条件过滤
        if (StringUtils.isNotBlank(agentSession.getAgentCode())) {
            for (AgentSession agentSession2 : agentSessionList) {
                if (agentSession2.getAgentCode().equals(agentSession.getAgentCode())) {
                    agentSessionListShow.add(agentSession2);
                }
            }
        } else {
            agentSessionListShow = agentSessionList;
        }
        for (AgentSession agentSession2 : agentSessionListShow) {
            AgentSessionVO agentSessionVO = new AgentSessionVO();
            agentSessionVO.setAgentCode(agentSession2.getAgentCode());
            agentSessionVO.setLstHeartBeatTs(String.valueOf(agentSession2.getLstHeartBeatTs()));
            agentSessionVO.setRegisterTs(agentSession2.getRegisterTs());
            agentSessionVO.setStatus(agentSession2.getStatus());
            agentSessionVOList.add(agentSessionVO);
        }
        // 结果分页
        return RamHelper.formatAgentListPage(agentSessionVOList, page);
    }

    /**
     * 查询内存节点map
     *
     * @param agentSession
     * @param page
     * @return
     */
    public List<AgentSessionVO> qryAgentSessionMap(AgentSessionVO agentSession, Page page) {
        List<AgentSessionVO> agentSessionVOList = new ArrayList<AgentSessionVO>();
        List<AgentSession> agentSessionList = new ArrayList<AgentSession>();
        List<AgentSession> agentSessionListShow = new ArrayList<AgentSession>();
        Map<String, AgentSession> agentSessionMap = agentManager.getAgentSessionMap();
        for (String agentCode : agentSessionMap.keySet()) {
            agentSessionList.add(agentSessionMap.get(agentCode));
        }
        // 条件过滤
        if (StringUtils.isNotBlank(agentSession.getAgentCode())) {
            for (AgentSession agentSession2 : agentSessionList) {
                if (agentSession2.getAgentCode().equals(agentSession.getAgentCode())) {
                    agentSessionListShow.add(agentSession2);
                }
            }
        } else {
            agentSessionListShow = agentSessionList;
        }
        for (AgentSession agentSession2 : agentSessionListShow) {
            AgentSessionVO agentSessionVO = new AgentSessionVO();
            agentSessionVO.setAgentCode(agentSession2.getAgentCode());
            agentSessionVO.setLstHeartBeatTs(String.valueOf(agentSession2.getLstHeartBeatTs()));
            agentSessionVO.setRegisterTs(agentSession2.getRegisterTs());
            agentSessionVO.setStatus(agentSession2.getStatus());
            agentSessionVOList.add(agentSessionVO);
        }
        // 结果分页
        return RamHelper.formatAgentListPage(agentSessionVOList, page);
    }

    /**
     * @Method: getAgentPath <br>
     * @Param: [agentConf] <br>
     * @Return: java.lang.String <br>
     * @Description：查询agent日志路径<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/7/23 10:29 <br>
     * @Version： V1.0<br>
     */
    public String getAgentPath(AgentConf agentConf) {
        String back = "";
        try {
            String url = "http://" + agentConf.getAgentIp() + ":" + agentConf.getAgentPort() + "/agent/getAgentPath";
            back = HttpUtils.httpJsonGet(url, null);
        } catch (Exception e) {
            log.error("查询agent日志路径失败，原因:{}", e.getMessage(), e);
        }
        return back;
    }

    private void initAgentConf(AgentConf agentConf){
        agentConf.setUpTs(HdrsDateUtil.getCurrentTime());
        agentConf.setPkId(BaseUtil.getPkId());
        agentConf.setCrtUser(BaseUtil.getUserId());
        agentConf.setUpUser(BaseUtil.getUserId());
        //初始化状态都是未开启
        agentConf.setAgentStatus(Const.AGENT_DEFAULT_STATUS);
        agentConf.setAgentHaStatus(Const.AGENT_HA_STATUS_STOP);
        //封装agentCode
        String agentCode = "AG" + BaseUtil.getPkId().substring(0, 5).toUpperCase();
        agentConf.setAgentCode(agentCode);
    }

    @Transactional
    public void saveAndInstall(AgentConf agentConf) {
        log.info("进入了AgentConfService类中的saveAndInstall方法");
        // 1.保存调度服务配置信息
        this.initAgentConf(agentConf);
        this.agentConfDao.add(agentConf);

        // 2.发布调度服务
        this.install(agentConf);
    }

    private void install(AgentConf agentConf){
        BizAgentModel model = this.buildbBzAgentModel(agentConf);
        BaseRespInfo respInfo = this.bizAgentService.install(model);

        // 3.发布成功后更新调度服务状态
        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
            agentConf.setAgentStatus(Const.AGENT_ENABLE_STATUS);
            this.update(agentConf);
        }
    }

    @Transactional
    public void saveAll(AgentServerVo agentServerVo) {
        log.info("进入了AgentConfService类中的saveAndInstall方法");
        // 1.保存管理AGENT配置
        AgentInfModel agentInfModel = agentServerVo.getAgentInfModel();
        agentInfModel.setCrtUser(BaseUtil.getUserName());
        agentInfModel.setUpUser(BaseUtil.getUserName());
        agentInfService.add(agentInfModel);

        // 2.保存调度服务配置信息
        this.initAgentConf(agentServerVo.getAgentConf());
        this.agentConfDao.add(agentServerVo.getAgentConf());
    }

    @Transactional
    public void saveAndInstallAll(AgentServerVo agentServerVo) throws Exception {
        log.info("进入了AgentConfService类中的saveAndInstall方法");
        // 1.保存管理AGENT和调度服务的配置信息
        this.saveAll(agentServerVo);
        // 2.发布管理AGENT
        AgentInfDto agentInfDto = new AgentInfDto();
        agentInfDto.setAgentInfModel(agentServerVo.getAgentInfModel());
        agentInfDto.setOptUser(BaseUtil.getUserName());
        agentInfService.install(agentInfDto);
        // 3.发布调度服务
        this.install(agentServerVo.getAgentConf());
    }

    private BizAgentModel buildbBzAgentModel(AgentConf agentConf){
        BizAgentModel bizAgentModel = new BizAgentModel();
        bizAgentModel.setAppType(Const.AGENT_NAME);
        bizAgentModel.setActName(Const.AGENT_INSTALL);
        bizAgentModel.setAgentHost(agentConf.getAgentIp());
        bizAgentModel.setAgentPort(agentConf.getAgentPort());
        bizAgentModel.setAgentCode(agentConf.getAgentCode());
        bizAgentModel.setAgentName(agentConf.getAgentName());
        bizAgentModel.setVersion(agentConf.getServerVer());
        return bizAgentModel;
    }

    public BaseRespInfo install(BizAgentModel bizAgentModel){
        BaseRespInfo respInfo = this.bizAgentService.install(bizAgentModel);
        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
            this.updateAgentStatus(bizAgentModel.getAgentCode(), Const.AGENT_ENABLE_STATUS);
        }else {
            this.updateAgentStatus(bizAgentModel.getAgentCode(), Const.AGENT_INSTALL_FAIL_STATUS);
        }
        return respInfo;
    }

//    public BaseRespInfo start(BizAgentModel bizAgentModel){
//        BaseRespInfo respInfo = this.bizAgentService.start(bizAgentModel);
//        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
//            this.updateAgentStatus(bizAgentModel.getAgentCode(), Const.AGENT_ENABLE_STATUS);
//        }
//        return respInfo;
//    }
//
//    public BaseRespInfo stop(BizAgentModel bizAgentModel){
//        BaseRespInfo respInfo = this.bizAgentService.stop(bizAgentModel);
//        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
//            this.updateAgentStatus(bizAgentModel.getAgentCode(), Const.AGENT_STOP_STATUS);
//        }
//        return respInfo;
//    }
//
//    public BaseRespInfo restart(BizAgentModel bizAgentModel){
//        return this.bizAgentService.restart(bizAgentModel);
//    }
//
//    public BaseRespInfo upgrade(BizAgentModel bizAgentModel){
//        BaseRespInfo respInfo = this.bizAgentService.upgrade(bizAgentModel);
//        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
//            this.updateAgentVersion(bizAgentModel.getAgentCode(), respInfo.getRsd().toString());
//        }
//        return respInfo;
//    }
//
//    public BaseRespInfo restore(BizAgentModel bizAgentModel){
//        BaseRespInfo respInfo = this.bizAgentService.restore(bizAgentModel);
//        if (com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
//            this.updateAgentVersion(bizAgentModel.getAgentCode(), respInfo.getRsd().toString());
//        }
//        return respInfo;
//    }

    public AgentConf qryAgentConfByIpAndPort(String ip, String port){
        Map map = new HashMap();
        map.put("agentIp", ip);
        map.put("agentPort", port);
        return agentConfDao.qryAgentConf(map);
    }

    public AgentConf qryAgentConfByName(String agentName){
        Map map = new HashMap();
        map.put("agentName", agentName);
        return agentConfDao.qryAgentConf(map);
    }

    public boolean checkAgentPort(AgentConf agentConf){
        AgentConf dbAgentConf = this.qryAgentConfByIpAndPort(agentConf.getAgentIp(), agentConf.getAgentPort());
        return dbAgentConf == null || dbAgentConf.getPkId().equals(agentConf.getPkId());
    }

    public AgentSessionResponseDto qryAgentSessionInfo(String agentCode){
        AgentSessionResponseDto agentSessionResponseDto = new AgentSessionResponseDto();
        AgentSession agentSession = agentManager.getAgentSession(agentCode);
        if (agentSession != null){
            agentSessionResponseDto.setAgentCode(agentSession.getAgentCode());
            agentSessionResponseDto.setAgentName(agentSession.getAgentName());
            agentSessionResponseDto.setStatus(agentSession.getStatus());
            agentSessionResponseDto.setCurResNum(agentSession.getCurResNum().get());
            agentSessionResponseDto.setCurConcurrentNum(agentSession.getCurConcurrentNum().get());
            if (agentSession.getAgentConf() != null){
                agentSessionResponseDto.setResTotal(agentSession.getAgentConf().getResNum());
                agentSessionResponseDto.setConcurrentTotal(agentSession.getAgentConf().getConcurrentNum());
                agentSessionResponseDto.setAgentHost(agentSession.getAgentConf().getAgentIp());
                agentSessionResponseDto.setAgentPort(agentSession.getAgentConf().getAgentPort());
            }
            agentSessionResponseDto.setAppConfList(agentSession.getAppConfList());
            agentSessionResponseDto.setPeriodRunningList(agentSession.getPeriodRunningList());
            agentSessionResponseDto.setCronRunningList(agentSession.getCronRunningList());
            agentSessionResponseDto.setDeltaList(agentSession.getDeltaList());
        }
        return agentSessionResponseDto;
    }

    /**
     * 启动中心后，自动重启调度服务
     */
    public void restartEnabledAgents(){
        List<AgentConf> agentList = qryAgentConfList();
        for (AgentConf agent : agentList) {
            if(agent.getAgentStatus().equals(Const.AGENT_ENABLE_STATUS)){
                BizAgentModel bizAgentModel =iAgentToBizAgentConverter.toAgent(agent);
                BaseRespInfo respInfo = bizAgentService.restart(bizAgentModel);
                if(com.hex.ds.ra.common.constant.Const.HTTP_STATUS_OK.equals(respInfo.getCode())){
                    log.info("调度服务{}，启动成功",agent.getAgentCode());
                }else{
                    log.error("调度服务{},启动失败",agent.getAgentCode());
                }
            }
        }
    }

}
